<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang>
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/hcigmoid/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic|Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/hcigmoid/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/hcigmoid/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/hcigmoid/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/hcigmoid/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/hcigmoid/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/hcigmoid/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="scala,method,function,">





  <link rel="alternate" href="/hcigmoid/atom.xml" title="HCigmoid" type="application/atom+xml">






<meta name="description" content="1. 引子在 Spark 开发过程中，我们经常会定义一些 udf 函数，用于对 DataFrame 的列进行变换，例如： 123val thres = 3.0val log10Udf = udf &amp;#123; x: Long =&amp;gt; math.min(math.log10(x + 2.0), thres) &amp;#125;df.withColumn(&quot;newColumn&quot;, log10Udf($&quot;">
<meta name="keywords" content="scala,method,function">
<meta property="og:type" content="article">
<meta property="og:title" content="Scala 中函数与方法的差别">
<meta property="og:url" content="http://guyuecanhui.gitee.io/hcigmoid/2018/07/17/method-vs-function 2/index.html">
<meta property="og:site_name" content="HCigmoid">
<meta property="og:description" content="1. 引子在 Spark 开发过程中，我们经常会定义一些 udf 函数，用于对 DataFrame 的列进行变换，例如： 123val thres = 3.0val log10Udf = udf &amp;#123; x: Long =&amp;gt; math.min(math.log10(x + 2.0), thres) &amp;#125;df.withColumn(&quot;newColumn&quot;, log10Udf($&quot;">
<meta property="og:locale" content="default">
<meta property="og:updated_time" content="2020-04-30T16:47:10.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Scala 中函数与方法的差别">
<meta name="twitter:description" content="1. 引子在 Spark 开发过程中，我们经常会定义一些 udf 函数，用于对 DataFrame 的列进行变换，例如： 123val thres = 3.0val log10Udf = udf &amp;#123; x: Long =&amp;gt; math.min(math.log10(x + 2.0), thres) &amp;#125;df.withColumn(&quot;newColumn&quot;, log10Udf($&quot;">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/hcigmoid/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://guyuecanhui.gitee.io/hcigmoid/2018/07/17/method-vs-function 2/">





  <title>Scala 中函数与方法的差别 | HCigmoid</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="default">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/hcigmoid/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">HCigmoid</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">Watch, learn and practise</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/hcigmoid/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/hcigmoid/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/hcigmoid/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/hcigmoid/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/hcigmoid/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://guyuecanhui.gitee.io/hcigmoid/hcigmoid/2018/07/17/method-vs-function 2/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="古月残辉">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/hcigmoid/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="HCigmoid">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Scala 中函数与方法的差别</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-07-17T16:01:05+08:00">
                2018-07-17
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/hcigmoid/categories/编程/" itemprop="url" rel="index">
                    <span itemprop="name">编程</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/hcigmoid/2018/07/17/method-vs-function 2/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/hcigmoid/2018/07/17/method-vs-function 2/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i> 阅读数
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1.1k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  5
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="1-引子"><a href="#1-引子" class="headerlink" title="1. 引子"></a>1. 引子</h3><p>在 <strong>Spark</strong> 开发过程中，我们经常会定义一些 <code>udf</code> 函数，用于对 <strong>DataFrame</strong> 的列进行变换，例如：</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">val</span> thres = <span class="number">3.0</span></span><br><span class="line"><span class="keyword">val</span> log10Udf = udf &#123; x: <span class="type">Long</span> =&gt; math.min(math.log10(x + <span class="number">2.0</span>), thres) &#125;</span><br><span class="line">df.withColumn(<span class="string">"newColumn"</span>, log10Udf($<span class="string">"oldColumn"</span>)).show</span><br></pre></td></tr></table></figure>
<p>这里的 <code>log10Udf</code> 是个啥呢？我们去看 <code>udf</code> 的定义，会发现它返回的是一个 <code>UserDefinedFunction</code> 对象：</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">udf</span></span>[<span class="type">RT</span>: <span class="type">TypeTag</span>, <span class="type">A1</span>: <span class="type">TypeTag</span>](f: <span class="type">Function1</span>[<span class="type">A1</span>, <span class="type">RT</span>]): <span class="type">UserDefinedFunction</span> = &#123;</span><br><span class="line">    <span class="keyword">val</span> inputTypes = <span class="type">Try</span>(<span class="type">ScalaReflection</span>.schemaFor(typeTag[<span class="type">A1</span>]).dataType :: <span class="type">Nil</span>).toOption</span><br><span class="line">    <span class="type">UserDefinedFunction</span>(f, <span class="type">ScalaReflection</span>.schemaFor(typeTag[<span class="type">RT</span>]).dataType, inputTypes)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>可以确认一下：</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">scala&gt; log10Udf.getClass</span><br><span class="line">res1: <span class="type">Class</span>[_ &lt;: org.apache.spark.sql.expressions.<span class="type">UserDefinedFunction</span>] = <span class="class"><span class="keyword">class</span> <span class="title">org</span>.<span class="title">apache</span>.<span class="title">spark</span>.<span class="title">sql</span>.<span class="title">expressions</span>.<span class="title">UserDefinedFunction</span></span></span><br><span class="line"><span class="class"></span></span><br><span class="line"><span class="class"><span class="title">scala&gt;</span> <span class="title">log10Udf</span>.<span class="title">isInstanceOf</span>[java.lang.<span class="type">Object</span>]</span></span><br><span class="line"><span class="class"><span class="title">res2</span></span>: <span class="type">Boolean</span> = <span class="literal">true</span></span><br></pre></td></tr></table></figure>
<p>这里就引出了一个小小的疑问，我们平时 <code>def</code> 的东西也是个对象吗？例如我们尝试一下：</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">scala&gt; <span class="function"><span class="keyword">def</span> <span class="title">inc</span></span>(x:<span class="type">Int</span>) = x + <span class="number">1</span></span><br><span class="line">inc: (x: <span class="type">Int</span>)<span class="type">Int</span></span><br><span class="line"></span><br><span class="line">scala&gt; inc.isInstanceOf[java.lang.<span class="type">Object</span>]</span><br><span class="line">&lt;console&gt;:<span class="number">13</span>: error: missing argument list <span class="keyword">for</span> method inc</span><br><span class="line"><span class="type">Unapplied</span> methods are only converted to functions when a function <span class="class"><span class="keyword">type</span> <span class="title">is</span> <span class="title">expected</span>.</span></span><br><span class="line"><span class="class"><span class="title">You</span> <span class="title">can</span> <span class="title">make</span> <span class="title">this</span> <span class="title">conversion</span> <span class="title">explicit</span> <span class="title">by</span> <span class="title">writing</span> `<span class="title">inc</span> <span class="title">_</span>` <span class="title">or</span> `<span class="title">inc</span>(<span class="params">_</span>)` <span class="title">instead</span> <span class="title">of</span> `<span class="title">inc</span>`.</span></span><br><span class="line"><span class="class">       <span class="title">inc</span>.<span class="title">isInstanceOf</span>[java.lang.<span class="type">Object</span>]</span></span><br><span class="line"><span class="class">       <span class="title">^</span></span></span><br></pre></td></tr></table></figure>
<p>从上面的报错信息我们可以分析出来两点：</p>
<ol>
<li><code>def</code> 的结果并不是一个对象，而是一个 <strong>method</strong>；</li>
<li>可以通过 <code>_</code> 操作符将一个 <strong>method</strong> 转成一个 <strong>function</strong>；</li>
</ol>
<p>确认一下：</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">scala&gt; (inc _).isInstanceOf[java.lang.<span class="type">Object</span>]</span><br><span class="line">res3: <span class="type">Boolean</span> = <span class="literal">true</span></span><br><span class="line"></span><br><span class="line">scala&gt; (inc _).getClass</span><br><span class="line">res4: <span class="type">Class</span>[_ &lt;: <span class="type">Int</span> =&gt; <span class="type">Int</span>] = <span class="class"><span class="keyword">class</span> <span class="title">$$Lambda$1421/1772552470</span></span></span><br></pre></td></tr></table></figure>
<h3 id="2-method-vs-function"><a href="#2-method-vs-function" class="headerlink" title="2. method vs. function"></a>2. method vs. function</h3><p>一个很自然的问题就提出来了：<strong>method</strong> 和 <strong>function</strong> 有啥差别呢？可以去<a href="https://docs.scala-lang.org/glossary/index.html" target="_blank" rel="noopener">官方文档</a>上查询关键字 function：</p>
<blockquote>
<p>A function can be invoked with a list of arguments to produce a result. A function has a parameter list, a body, and a result type. <strong>Functions that are members of a class, trait, or singleton object are called methods.</strong> Functions defined inside other functions are called local functions. Functions with the result type of Unit are called procedures. Anonymous functions in source code are called function literals. <strong>At run time, function literals are instantiated into objects called function values.</strong></p>
</blockquote>
<p>简单的来讲，<strong>method</strong> 是定义在 <code>class</code>, <code>trait</code> 或者 <code>object</code> 里的 <strong>function</strong>，而匿名函数（Anonymous functions）会在运行时被实例化成 <strong>object</strong>。所谓的匿名函数就是没有名字的函数（-_-!），例如：<code>(x: Int) =&gt; x + 2</code> 就是一个匿名函数，我们可以将它赋值给一个变量：</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">val</span> inc2 = (x: <span class="type">Int</span>) =&gt; x + <span class="number">2</span></span><br></pre></td></tr></table></figure>
<p>把它写到一个类定义里，再尝试着编译一下，会得到这个匿名函数的定义：</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">public <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">test$$anonfun$1</span> <span class="keyword">extends</span> <span class="title">java</span>.<span class="title">lang</span>.<span class="title">Object</span> <span class="title">implements</span> <span class="title">scala</span>.<span class="title">Function1</span>,<span class="title">scala</span>.<span class="title">ScalaObject</span></span></span><br></pre></td></tr></table></figure>
<p>其中，值得关注的是这个匿名函数实现了 <strong>trait</strong> <code>scala.Function1</code>（实际上，<strong>scala</strong> 包里定义了 <code>Function0</code> ~ <code>Function22</code> 表示接受 0 ~ 22 个参数的函数），它的代码如下：</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@annotation</span>.implicitNotFound(msg = <span class="string">"No implicit view available from $&#123;T1&#125; =&gt; $&#123;R&#125;."</span>)</span><br><span class="line"><span class="class"><span class="keyword">trait</span> <span class="title">Function1</span>[@specialized(scala.<span class="type">Int</span>, scala.<span class="type">Long</span>, scala.<span class="type">Float</span>, scala.<span class="type">Double</span>) -<span class="type">T1</span>, @specialized(scala.<span class="type">Unit</span>, scala.<span class="type">Boolean</span>, scala.<span class="type">Int</span>, scala.<span class="type">Float</span>, scala.<span class="type">Long</span>, scala.<span class="type">Double</span>) +<span class="type">R</span>] <span class="keyword">extends</span> <span class="title">AnyRef</span> </span>&#123; self =&gt;</span><br><span class="line">  <span class="comment">/** Apply the body of this function to the argument.</span></span><br><span class="line"><span class="comment">   *  @return   the result of function application.</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">apply</span></span>(v1: <span class="type">T1</span>): <span class="type">R</span></span><br><span class="line">  <span class="meta">@annotation</span>.unspecialized <span class="function"><span class="keyword">def</span> <span class="title">compose</span></span>[<span class="type">A</span>](g: <span class="type">A</span> =&gt; <span class="type">T1</span>): <span class="type">A</span> =&gt; <span class="type">R</span> = &#123; x =&gt; apply(g(x)) &#125;</span><br><span class="line">  <span class="meta">@annotation</span>.unspecialized <span class="function"><span class="keyword">def</span> <span class="title">andThen</span></span>[<span class="type">A</span>](g: <span class="type">R</span> =&gt; <span class="type">A</span>): <span class="type">T1</span> =&gt; <span class="type">A</span> = &#123; x =&gt; g(apply(x)) &#125;</span><br><span class="line">  <span class="keyword">override</span> <span class="function"><span class="keyword">def</span> <span class="title">toString</span></span>() = <span class="string">"&lt;function1&gt;"</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>根据注释推测，这个匿名函数实际上就是定义了 <code>apply</code> 方法；当我们调用 <code>inc2(3)</code> 时，我们实际上是调用了这个对象的 <code>apply</code> 方法。确认一下：</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">val</span> inc2 = (x: <span class="type">Int</span>) =&gt; x + <span class="number">2</span></span><br><span class="line"><span class="keyword">val</span> anonfun = <span class="keyword">new</span> <span class="type">Function1</span>[<span class="type">Int</span>, <span class="type">Int</span>] &#123;</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">apply</span></span>(x: <span class="type">Int</span>): <span class="type">Int</span> = x + <span class="number">2</span></span><br><span class="line">&#125;</span><br><span class="line">assert(inc2(<span class="number">0</span>) == anonfun(<span class="number">0</span>))</span><br></pre></td></tr></table></figure>
<p>嗯，终于理顺了 ~ 好了，我们再用这个例子串一下：</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">scala&gt; <span class="function"><span class="keyword">def</span> <span class="title">inc</span></span>(x: <span class="type">Int</span>) = x + <span class="number">1</span></span><br><span class="line">inc: (x: <span class="type">Int</span>)<span class="type">Int</span></span><br><span class="line"></span><br><span class="line">scala&gt; <span class="keyword">val</span> inc2 = (x: <span class="type">Int</span>) =&gt; x + <span class="number">2</span></span><br><span class="line">inc2: <span class="type">Int</span> =&gt; <span class="type">Int</span> = $$<span class="type">Lambda</span>$<span class="number">1035</span>/<span class="number">948692477</span>@<span class="number">8</span>f2e3e6</span><br><span class="line"></span><br><span class="line">scala&gt; <span class="keyword">val</span> inc3 = inc _</span><br><span class="line">inc3: <span class="type">Int</span> =&gt; <span class="type">Int</span> = $$<span class="type">Lambda</span>$<span class="number">1042</span>/<span class="number">1739111611</span>@<span class="number">1</span>bb96449</span><br><span class="line"></span><br><span class="line">scala&gt; inc2.toString</span><br><span class="line">res0: <span class="type">String</span> = $$<span class="type">Lambda</span>$<span class="number">1035</span>/<span class="number">948692477</span>@<span class="number">8</span>f2e3e6</span><br><span class="line"></span><br><span class="line">scala&gt; inc.toString</span><br><span class="line">&lt;console&gt;:<span class="number">13</span>: error: missing argument list <span class="keyword">for</span> method inc</span><br><span class="line"><span class="type">Unapplied</span> methods are only converted to functions when a function <span class="class"><span class="keyword">type</span> <span class="title">is</span> <span class="title">expected</span>.</span></span><br><span class="line"><span class="class"><span class="title">You</span> <span class="title">can</span> <span class="title">make</span> <span class="title">this</span> <span class="title">conversion</span> <span class="title">explicit</span> <span class="title">by</span> <span class="title">writing</span> `<span class="title">inc</span> <span class="title">_</span>` <span class="title">or</span> `<span class="title">inc</span>(<span class="params">_</span>)` <span class="title">instead</span> <span class="title">of</span> `<span class="title">inc</span>`.</span></span><br><span class="line"><span class="class">       <span class="title">inc</span>.<span class="title">toString</span></span></span><br><span class="line"><span class="class">       <span class="title">^</span></span></span><br><span class="line"><span class="class"></span></span><br><span class="line"><span class="class"><span class="title">scala&gt;</span> <span class="title">val</span> <span class="title">inc4</span> </span>= inc</span><br><span class="line">&lt;console&gt;:<span class="number">12</span>: error: missing argument list <span class="keyword">for</span> method inc</span><br><span class="line"><span class="type">Unapplied</span> methods are only converted to functions when a function <span class="class"><span class="keyword">type</span> <span class="title">is</span> <span class="title">expected</span>.</span></span><br><span class="line"><span class="class"><span class="title">You</span> <span class="title">can</span> <span class="title">make</span> <span class="title">this</span> <span class="title">conversion</span> <span class="title">explicit</span> <span class="title">by</span> <span class="title">writing</span> `<span class="title">inc</span> <span class="title">_</span>` <span class="title">or</span> `<span class="title">inc</span>(<span class="params">_</span>)` <span class="title">instead</span> <span class="title">of</span> `<span class="title">inc</span>`.</span></span><br><span class="line"><span class="class">       <span class="title">val</span> <span class="title">inc4</span> </span>= inc</span><br><span class="line">                  ^</span><br></pre></td></tr></table></figure>
<h3 id="3-Take-aways"><a href="#3-Take-aways" class="headerlink" title="3. Take-aways"></a>3. Take-aways</h3><p>这篇短文主要比较了之前容易忽略的两个概念：<strong>method</strong> 和 <strong>function</strong> 的联系和细微的差别：</p>
<ol>
<li><strong>method</strong> 是定义在 <code>class</code>, <code>trait</code> 或者 <code>object</code> 里的 <strong>function</strong>；</li>
<li>在运行时，匿名函数会被实例化成 <strong>object</strong>，因此可以把匿名函数赋值给一个变量，调用匿名函数实际上是调用这个对象的 <code>apply</code> 方法；</li>
<li><strong>method</strong> 本身只是一段代码，并不会被实例化，也不能对它进行赋值等操作，但是 <strong>method</strong> 通过 <code>_</code> 操作符可以转换成一个 <strong>function</strong> 类型；</li>
</ol>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/hcigmoid/tags/scala/" rel="tag"># scala</a>
          
            <a href="/hcigmoid/tags/method/" rel="tag"># method</a>
          
            <a href="/hcigmoid/tags/function/" rel="tag"># function</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/hcigmoid/2018/07/17/method-vs-function/" rel="next" title="Scala 中函数与方法的差别">
                <i class="fa fa-chevron-left"></i> Scala 中函数与方法的差别
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/hcigmoid/2018/07/20/currying/" rel="prev" title="柯里化 (Currying) 及其应用">
                柯里化 (Currying) 及其应用 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">古月残辉</p>
              <p class="site-description motion-element" itemprop="description">总结心得</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/hcigmoid/archives/">
              
                  <span class="site-state-item-count">62</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/hcigmoid/categories/index.html">
                  <span class="site-state-item-count">6</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/hcigmoid/tags/index.html">
                  <span class="site-state-item-count">70</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/hcigmoid/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="mailto:guyuecanhui@icloud.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-引子"><span class="nav-number">1.</span> <span class="nav-text">1. 引子</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-method-vs-function"><span class="nav-number">2.</span> <span class="nav-text">2. method vs. function</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-Take-aways"><span class="nav-number">3.</span> <span class="nav-text">3. Take-aways</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2018 &mdash; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">古月残辉</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">105.3k</span>
  
</div>









<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i> 访问人数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i> 总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/hcigmoid/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/hcigmoid/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/hcigmoid/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/hcigmoid/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/hcigmoid/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/hcigmoid/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/hcigmoid/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/hcigmoid/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/hcigmoid/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/hcigmoid/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/hcigmoid/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/hcigmoid/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/hcigmoid/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: '6du4Ppc2TvUuhcccRHSDNH2v-gzGzoHsz',
        appKey: 'zOKNml4W1Bq3OTzEuLt5hUjI',
        placeholder: '感谢阅读！欢迎评论！',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/hcigmoid/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  
  


  

  

</body>
</html>
